import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { headers } from '@/utils'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    menuIds: [],
    uploadHeaders: headers,
    roleName: '', // roleName
    imId: '', // imId
    imToken: '', // imToken
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_UPLOADHEADERS: (state, uploadHeaders) => {
    state.uploadHeaders = uploadHeaders
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLENAME: (state, roleName) => {
    state.roleName = roleName
  },
  SET_MEMUIDS: (state, menuIds) => {
    state.menuIds = menuIds
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_IMID: (state, imId) => {
    state.imId = imId
  },
  SET_IMTOKEN: (state, imToken) => {
    state.imToken = imToken
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        const { name, menuIds, token, imId, imToken } = response.data
        console.log(name, menuIds, token, imId, imToken)
        commit('SET_NAME', name)
        commit('SET_MEMUIDS', menuIds)
        commit('SET_TOKEN', token)
        commit('SET_IMID', imId)
        commit('SET_IMTOKEN', imToken)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({}).then(res => {
        const { name, menuIds, roleName } = res.data

        if (!res) {
          return reject('获取失败，请重新登录.')
        }

        headers['X-App-Token'] = getToken()
        commit('SET_UPLOADHEADERS', headers)

        commit('SET_NAME', name)
        commit('SET_ROLENAME', roleName)
        commit('SET_MEMUIDS', menuIds)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout({}).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

